package top.pcat.service;

import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.exceptions.JedisException;
import top.pcat.entity.ChatRoom;
import top.pcat.util.RedisPoolUtil;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
public class ChatRoomService {


    public void newchatRoom(String name,long rooId){
        JedisPool jedisPool = RedisPoolUtil.getRedisPoolUtil();
        Jedis jedis = jedisPool.getResource();

        ChatRoom room = new ChatRoom();
        room.setRoomId(rooId);
        room.setRoomName(name);

        String key = "chatRoom";
        jedis.hset(key, String.valueOf(room.getRoomId()), room.getRoomName());

        jedis.close();
    }

    public void addNewMem(long rooId,String mem){
        Jedis jedis = RedisPoolUtil.getJedis();

        jedis.zadd("chatRoom-"+rooId, rooId, mem);

        jedis.close();
    }

    public void removeMem(){}

    public List<ChatRoom> getRoomList(){
        JedisPool jedisPool = RedisPoolUtil.getRedisPoolUtil();
        Jedis jedis = jedisPool.getResource();
        Map<String, String> stringStringMap = jedis.hgetAll("chatRoom");
        List<ChatRoom> chatRoomList = stringStringMap.entrySet()
                .stream()
                .map(entry -> new ChatRoom(entry.getKey(), entry.getValue()))
                .collect(Collectors.toList());

        for (ChatRoom key : chatRoomList){
            log.info(String.valueOf(key));
        }
        return chatRoomList;
    }


    public void getRoomMem(){

        JedisPool jedisPool = RedisPoolUtil.getRedisPoolUtil();
        Jedis jedis = jedisPool.getResource();
        List<String> chatRoomKeys = jedis.zrange("chat-room:1", 0, -1);

        for (String m : chatRoomKeys){
            System.out.println(m);
        }

        for (String key : chatRoomKeys) {
            System.out.println("key " + key);
            java.util.Map<String, String> chatRoom = jedis.hgetAll(key);
            System.out.println(chatRoom.get("name") + ": " + chatRoom.get("members"));
            String[] members = chatRoom.get("members").split("，");

            for (String m : members){
                System.out.println(m);
            }
        }
    }


    // 添加一个用户到指定聊天室
    public void addUserToChatroom(long chatroomId, String userId, String serverId) {
        JedisPool jedisPool = RedisPoolUtil.getRedisPoolUtil();
        try (Jedis jedis = jedisPool.getResource()) {
            // 设置聊天室Hash字段中的成员ID和所在服务器ID
            jedis.hset("chatroom:" + chatroomId, userId, serverId);
            // 将用户ID添加到所在服务器的在线用户集合中
            jedis.sadd("server:" + serverId + ":online_users", userId);
        } catch (JedisException e) {
            // 异常处理
            e.printStackTrace();
        }
    }

    // 获取指定聊天室中所有成员和所在服务器信息的Map
    public static Map<String, String> getChatroomMembers(long chatroomId) {
        JedisPool jedisPool = RedisPoolUtil.getRedisPoolUtil();
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.hgetAll("chatroom:" + chatroomId);
        } catch (JedisException e) {
            // 异常处理
            e.printStackTrace();
            return Collections.emptyMap();
        }
    }

    public static String getRandomChatroomMembers(long chatroomId) {
        JedisPool jedisPool = RedisPoolUtil.getRedisPoolUtil();
        try (Jedis jedis = jedisPool.getResource()) {
            String hashKey = jedis.hrandfield("chatroom:" + chatroomId, 1).get(0);
            String hashValue = jedis.hget("chatroom:" + chatroomId, hashKey);
            return hashKey+":"+hashValue;
        } catch (JedisException e) {
            // 异常处理
            e.printStackTrace();
            return null;
        }
    }

    // 获取指定服务器上的所有在线用户ID
    public Set<String> getOnlineUsersInServer(String serverId) {
        JedisPool jedisPool = RedisPoolUtil.getRedisPoolUtil();
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.smembers("server:" + serverId + ":online_users");
        } catch (JedisException e) {
            // 异常处理
            e.printStackTrace();
            return Collections.emptySet();
        }
    }

    // 将指定用户从聊天室中删除
    public void removeUserFromChatroom(long chatroomId, String userId) {
        JedisPool jedisPool = RedisPoolUtil.getRedisPoolUtil();
        try (Jedis jedis = jedisPool.getResource()) {
            // 获取用户所在的服务器ID和聊天室ID
            if (chatroomId != 0) {
                log.info("redis移除用户"+chatroomId+":userid="+userId);
                // 从聊天室Hash数据结构中删除该用户字段
                long hdel = jedis.hdel("chatroom:" + chatroomId, userId);
                if (hdel > 0 ){
                    log.info("redis移除成功"+chatroomId+":userid="+userId);
                }else{

                    log.info("redis移除失败 用户已经不在了"+chatroomId+":userid="+userId+" : "+hdel);
                }
            }else {

                log.info("redis移除失败 房间不存在"+chatroomId);
            }
        } catch (JedisException e) {
            // 异常处理
            e.printStackTrace();
        }
    }


}
